package com.zhijiaoyun.aliyun.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * @author shisfish
 * @date 2018/1/23
 */
public class OSSManager {

    private static OSSClient ossClient;

    public static OSSClient getOSSClient() {
        if (ossClient == null) {
            ossClient = new OSSClient(OSSConfig.HTTP + OSSConfig.END_POINT, OSSConfig.ACCESS_KEY_ID, OSSConfig.ACCESS_KEY_SECRET);
        }
        return ossClient;
    }

    /**
     * 返回上传成功的文件路径
     *
     * @param key      oss 文件名
     * @param filePath 上传的文件地址
     * @param fileDir  上传的文件夹
     * @param fileName 上传的文件名
     * @return
     * @throws FileNotFoundException
     */
    public static String updateFile(String key, String filePath, String fileDir, String fileName) throws FileNotFoundException {
        putObject(key, filePath);
        return OSSConfig.HTTP + OSSConfig.BUCKET_NAME + "." + OSSConfig.END_POINT + File.separator + fileDir + fileName;
    }

    /**
     * 返回上传成功的文件路径
     *
     * @param key      oss 文件名
     * @param file     上传的文件
     * @param fileDir  上传的文件夹
     * @param fileName 上传的文件名
     * @return
     * @throws FileNotFoundException
     */
    public static String updateFile(String key, File file, String fileDir, String fileName) throws FileNotFoundException {
        putObject(key, file);
        return OSSConfig.HTTP + OSSConfig.BUCKET_NAME + "." + OSSConfig.END_POINT + File.separator + fileDir + fileName;
    }

    public static PutObjectResult putObject(String key, String filePath) throws FileNotFoundException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
        return putObject(key, file);
    }

    public static PutObjectResult putObject(OSSClient ossClient, String key, String filePath) throws FileNotFoundException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
        return putObject(ossClient, key, file);
    }

    public static PutObjectResult putObject(String key, File file) {
        return putObject(getOSSClient(), key, file);
    }

    public static PutObjectResult putObject(OSSClient ossClient, String key, File file) {
        return ossClient.putObject(new PutObjectRequest(OSSConfig.BUCKET_NAME, key, file));
    }
    
    public static void deleteFile(String filePath) {
    	deleteFile(getOSSClient(), filePath);
    }
    
    public static void deleteFile(OSSClient ossClient, String filePath) {
    	String key = filePath.replace(OSSConfig.HTTP, "").replace(OSSConfig.BUCKET_NAME, "").replace(OSSConfig.END_POINT, "").substring(2);
    	boolean exists = ossClient.doesObjectExist(OSSConfig.BUCKET_NAME, key);
    	if (exists) {
    		ossClient.deleteObject(OSSConfig.BUCKET_NAME, key);
    	}
    }

}
